package org.soenea.doitall.domain.model.user.mapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.mapper.DomainObjectNotFoundException;
import org.dsrg.soenea.domain.mapper.IdentityMap;
import org.dsrg.soenea.uow.UoW;
import org.soenea.doitall.domain.model.user.*;
import org.soenea.doitall.domain.model.user.data.*;

public class UserInputMapper {

	public static User find(String userName, String password) throws MapperException,
	DomainObjectNotFoundException {
	try {
		ResultSet rs = UserFinder.findByCredentials(userName, password);
		if (rs.next()) {
			return getUser(rs);
		} else {
			throw new DomainObjectNotFoundException("The username and password entered is not found!");
		}
	} catch (SQLException e) {
		throw new MapperException(e);
	    }
    }
	
	public static List<User> findByGroupID(long id) throws MapperException {
		ArrayList<User> users = new ArrayList<User>();
		try {
			ResultSet rs = UserFinder.findByGroupID(id);
			while (rs.next()) {
				users.add(getUser(rs));
			} 
		} catch (SQLException e) {
			throw new MapperException(e);
		}
		return users;
	}	
	
	public static User find(long id) throws MapperException,
	DomainObjectNotFoundException {
	try {
		if (IdentityMap.has(id, User.class))
			return IdentityMap.get(id, User.class);		
		
		ResultSet rs = UserFinder.find(id);
		if (rs.next()) {
			return getUser(rs);
		} else {
			throw new DomainObjectNotFoundException("Person " + id + " is not found!");
		}
	} catch (SQLException e) {
		throw new MapperException(e);
	}
	}
	
	public static User find(String userName) throws MapperException, DomainObjectNotFoundException {
		try {
			ResultSet rs = UserFinder.find(userName);
			if (rs.next()) {
				return getUser(rs);
			} else {
				throw new DomainObjectNotFoundException("Person with username '" + userName + "' is not found!");
			}
		} catch (SQLException e) {
			throw new MapperException(e);
		}
	}
	
	private static User getUser(ResultSet rs) throws SQLException {
		User result = new User(rs.getLong("p.userId"),rs.getString("p.userName"),rs.getString("p.password"),rs.getInt("p.groupID"), 
				rs.getString("p.firstName"),rs.getString("p.lastName"),rs.getLong("p.version"), rs.getBoolean("p.admin"));
		UoW.getCurrent().registerClean(result);
		return result;
	}
}
